#include "../StdInc.h"

namespace GSTrader
{
	namespace TradeStrategy
	{
		CProviderManager::CProviderManager(CFramework* pFramework) : m_pFramework(pFramework)
		{
		}


		CProviderManager::~CProviderManager()
		{
			RemoveAllProvider();
		}

		size_t CProviderManager::GetProviderSize()
		{
			return m_mapProvider.size();
		}

		CProvider* CProviderManager::GetProvider(int nId)
		{
			if (nId < 0)
				return nullptr;

			auto it = m_mapProvider.find(nId);
			if (it == m_mapProvider.end())
				return NULL;

			return it->second;
		}

		bool CProviderManager::AddProvider(CProvider* pProvider)
		{
			if (pProvider == NULL || pProvider->m_pConnectionInfo == NULL)
				return false;

			int nProviderId = pProvider->GetProviderId();
			auto it = m_mapProvider.find(nProviderId);
			if (it != m_mapProvider.end())
			{
				return false;
			}
			else
			{
				m_mapProvider[nProviderId] = pProvider;
				return true;
			}
		}

		void CProviderManager::RemoveProvider(CProvider* pProvider)
		{
			if (pProvider == NULL)
				return;

			auto it = m_mapProvider.find(pProvider->GetProviderId());
			if (it == m_mapProvider.end())
				return;

			if (pProvider->IsConnectionProvider())
			{
				CConnectionProvider* pConnectionProvider = (CConnectionProvider*)pProvider;
//				if (pConnectionProvider->IsConnect())
				{
					pConnectionProvider->DisConnect();
				}
			}

			CConnectionProvider* pConnProvider = dynamic_cast<CConnectionProvider*>(pProvider);
			if (pConnProvider)
			{
				m_pFramework->m_pStrategySessionManager->OnRemoveProvider(pConnProvider);
			}
			

			m_mapProvider.erase(it);
			_delete(pProvider);
		}

		void CProviderManager::GetAllProvider(vector<CProvider*>& vProvider)
		{
			vProvider.clear();
			for (auto it : m_mapProvider)
			{
				vProvider.push_back(it.second);
			}
		}

		void CProviderManager::RemoveAllProvider()
		{
			map<int, CProvider*>::reverse_iterator it;
			for (it = m_mapProvider.rbegin(); it != m_mapProvider.rend(); it++)
			{
				CProvider* pProvider = it->second;
				if (pProvider->IsConnectionProvider())
				{
					CConnectionProvider* pConnectionProvider = (CConnectionProvider*)(pProvider);
				//	if (pConnectionProvider->IsConnect())
					{
						pConnectionProvider->DisConnect();
						m_pFramework->m_pStrategySessionManager->OnRemoveProvider(pConnectionProvider);
					}

					_delete(pProvider)
				}
			}
			m_mapProvider.clear();
		}
	}
}